//
//  BMSAuthSDK.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSAuthSDK.h"
#import "BMSAuthManager.h"
#import "BMSAPIService.h"
#import "BMSInitializer.h"
#import "BMSPopupQueueManager.h"
#import "BMSPrivacyExitView.h"
#import "BMSDeviceInfo.h"
#import "BMSAppInfoHelper.h"
#import "BMSPrivate.h"
#import "BMSKeychain.h"
#import "BMSLinkOpener.h"
#import "BMSVibrator.h"
#import "GroMoreSDKManager.h"
#import "WDGroMoreTipManager.h"
#import "BMSLifecycleManager.h"
#import "BMSRealnamePopupView.h"

#import <AFNetworking/AFNetworkReachabilityManager.h>


@interface BMSAuthSDK()
@property (nonatomic, assign) BOOL hasInitialized;

@end

static BMSAuthSDK *instance = nil;

@implementation BMSAuthSDK

+ (BMSAuthSDK *)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BMSAuthSDK alloc]init];
    });
    return instance;
}

#pragma mark ------------ public method -----------

-(void)checkIPBlockStatusWithAppName:(NSString *)appName channel:(NSString *)channel version:(NSString *)version ip:(NSString *)ip success:(void (^)(NSDictionary * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    [BMSAPIService checkIPBlockStatusWithAppName:appName channel:channel version:version ip:ip success:success failure:failure];
}

- (void)fetchOfficialHolidaysWithSuccess:(void (^)(id _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure {
    [BMSAPIService fetchOfficialHolidaysWithSuccess:success failure:failure];
}
- (void)initSDKCompletion:(BMSInitCompletion)completion {
    [BMSLifecycleManager isFirstLaunchByInstallDate];
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];

    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable || status == AFNetworkReachabilityStatusUnknown) {
            [[WDGroMoreTipManager manager] show];
        } else {
            [[WDGroMoreTipManager manager] remove];

            // ✅ 防止重复初始化
            if (!self.hasInitialized) {
                self.hasInitialized = YES;

                [self initBMSSDKCompletion:completion];

                [[GroMoreSDKManager shared] initGroMoreWithUuid:[WDGroMorePublic manager].uuid
                                                      isSuccess:[WDGroMorePublic manager].success];
            }
        }
    }];
    [mgr startMonitoring];
}
- (void)initBMSSDKCompletion:(BMSInitCompletion)completion {
    // 基础信息设置
    [BMSInitializer shared].appName = [BMSAppInfoHelper bmsAppNameForInfoPlistFile];
    [BMSInitializer shared].version = [BMSAppInfoHelper bmsAppVersionForInfoPlistFile];
    [BMSInitializer shared].channel = [BMSAppInfoHelper bmsChannelForSDKConfigFile];
    
    // 启动SDK
    [BMSInitializer startWithAppName:[BMSAppInfoHelper bmsAppNameForInfoPlistFile]
                             version:[BMSAppInfoHelper bmsAppVersionForInfoPlistFile]
                             channel:[BMSInitializer shared].channel
                          completion:^{
        [self handleInitializationFlowWithCompletion:completion];
    }];
}

#pragma mark - 初始化流程处理

- (void)handleInitializationFlowWithCompletion:(BMSInitCompletion)completion {
    // 检查是否需要显示隐私弹窗
    if ([self shouldShowPrivacyPopup]) {
        [self handlePrivacyPopupWithCompletion:completion];
    } else {
        // 已同意隐私，直接进入登录流程
        [self proceedWithLoginAndRealnameWithCompletion:completion];
    }
}


#pragma mark - 隐私弹窗处理

- (BOOL)shouldShowPrivacyPopup {
    return ![BMSInitializer shared].didAgreePrivacy &&
           [BMSInitializer shared].launchModel.openPri == 0;
}

- (void)handlePrivacyPopupWithCompletion:(BMSInitCompletion)completion {
    BMSAuthManager *manager = [[BMSAuthManager alloc] init];
    [manager showPrivacyPopupWithCompletion:^(BOOL agreed) {
        // 记录用户操作
        [self recordPrivacyClickEvent:agreed];
        
        if (agreed) {
            // 用户同意隐私协议
            [self proceedWithLoginAndRealnameWithCompletion:completion];
        } else {
            // 用户拒绝隐私协议
            [self handlePrivacyRejectionWithCompletion:completion];
        }
    }];
}

- (void)handlePrivacyRejectionWithCompletion:(BMSInitCompletion)completion {
    BMSAuthManager *exitManager = [[BMSAuthManager alloc] init];
    [exitManager showExitPopupWithCompletion:^(BOOL retry) {
        if (retry && [self shouldRetryAfterPrivacyRejection]) {
            // 用户选择重试且满足条件
            [self proceedWithLoginAndRealnameWithCompletion:completion];
        } else {
            // 直接返回失败结果
            [self callCompletionWithDefaultValues:completion];
        }
    }];
}

#pragma mark - 登录和实名流程

- (void)proceedWithLoginAndRealnameWithCompletion:(BMSInitCompletion)completion {
    [[BMSInitializer shared] handlePrivacyAgreedAndLoginWithCompletion:^(BOOL loginSuccess) {
        if (!loginSuccess) {
            // 登录失败直接回调
            [self callCompletionWithLoginSuccess:NO didRealname:NO completion:completion];
//            return;
        }

        if ([BMSInitializer shared].isTeenager && ![[BMSAntiAddictionManager shared] isAllowedToPlay]) {
            NSLog(@"🚫 未成年人：弹窗提示退出，不能玩");
//            BMSAuthManager *manager = [[BMSAuthManager alloc]init];
            [BMSAuthManager showForceExitPopup];
            
            [self callCompletionWithLoginSuccess:YES didRealname:YES completion:completion]; // 已实名，但是未成年
            return;
        } else if([BMSInitializer shared].isTeenager && [[BMSAntiAddictionManager shared]isAllowedToPlay]) {
            NSLog(@"🚫 未成年人,节假日，可以游玩时间");
            [[BMSAntiAddictionManager shared]scheduleDailyAntiAddictionCheck];
        }

        if ([self shouldPerformRealname]) {
            // 尚未实名，弹实名弹窗
            [self handleRealnameIfNeededWithCompletion:^(BOOL didRealname) {
                [self callCompletionWithLoginSuccess:YES
                                         didRealname:didRealname
                                          completion:completion];
            }];
        } else {
            // 已实名
            [self callCompletionWithLoginSuccess:YES didRealname:YES completion:completion];
        }
    }];
}

#pragma mark - 辅助方法

- (void)recordPrivacyClickEvent:(BOOL)agreed {
    [[BMSOpMergeReporter shared] addEvent:[BMSOpMergeEventBuilder
        event_userActionWithAct:BMS_EVENT_BASE_PRIVACY_CLICK
                    description:BMS_WDS_PRIVACY_POPUP_ACTION
                           tab1:[NSString stringWithFormat:@"%d", agreed]
                           tab2:@""
                           tab3:@""
                           tabN:@{}]];
}

- (BOOL)shouldRetryAfterPrivacyRejection {
    return [BMSInitializer shared].launchModel.rnAuth == 0;
}

- (BOOL)shouldPerformRealname {
    return [BMSInitializer shared].launchModel.rnAuth == 0;
}

- (void)callCompletionWithLoginSuccess:(BOOL)loginSuccess
                           didRealname:(BOOL)didRealname
                            completion:(BMSInitCompletion)completion {
    if (completion) {
        completion(loginSuccess,
                   YES, // privacyAgreed
                   [BMSInitializer shared].idfaAuthorized,
                   didRealname,
                   [BMSInitializer shared].uuid);
    }
}

- (void)callCompletionWithDefaultValues:(BMSInitCompletion)completion {
    if (completion) {
        completion(YES,    // success - 根据业务需求调整
                   YES,    // privacyAgreed
                   NO,     // trackingAuthorized
                   NO,     // didRealname
                   [BMSKeychain WDKeychainGetUUID]);
    }
}

-(void)showPrivacyPopupWithCompletion:(void (^)(BOOL))completion {
    BMSAuthManager *manager = [[BMSAuthManager alloc]init];
    [manager showPrivacyPopupWithCompletion:^(BOOL agreed) {
        
    }];
}

- (void)showRealnamePopupWithCompletion:(void (^)(BOOL success))completion {
    BMSAuthManager *manager = [[BMSAuthManager alloc]init];
    [manager showRealnamePopupWithCompletion:^(BOOL success) {
        completion(success);
    }];
}

- (NSString *)BMSUUID {
    return [BMSInitializer shared].loginModel.uuid ? [BMSInitializer shared].loginModel.uuid : [[BMSDeviceInfo shared]UUID];
}

- (void)openTerms {
    [BMSLinkOpener openTerms];
}

- (void)openPrivacy {
    [BMSLinkOpener openPrivacy];
}

-(void)openH5WithUrl:(NSString *)url {
    [BMSLinkOpener openURL:url];
}

/// 单次震动，默认样式（短促）
- (void)vibrateOnce {
    [BMSVibrator vibrateOnce];
}

/// 自定义震动（使用 CoreHaptics 模拟间隔+时长震动）
- (void)vibrateWithPattern:(NSArray<NSNumber *> *)pattern
                    repeat:(NSInteger)repeat {
    [BMSVibrator vibrateWithPattern:pattern repeat:repeat];
    
}

/// 取消震动（如果可取消）
- (void)vibrateCancel {
    [BMSVibrator vibrateCancel];
}


- (void)handleRealnameIfNeededWithCompletion:(void(^)(BOOL didRealname))completion {
    [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_REALNAME_JSON description:BMS_WDS_REALNAME_CONFIG_FETCH tab1:[NSString stringWithFormat:@"%ld",(long)[BMSInitializer shared].launchModel.rnAuth] tab2:@"" tab3:@"" tabN:@{}]];
    BOOL didRealnameAuth = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSKeyRealnameAuth];
    if (didRealnameAuth) {
        if (completion) completion(YES);
        return;
    }
    
    BOOL isFirstLaunch = [BMSLifecycleManager isFirstLaunchByInstallDate];   // 是否首次启动
    BOOL hasForcedRealname = [[NSUserDefaults standardUserDefaults] boolForKey:kBMSForcedRealname]; // 是否已弹过
    BOOL shouldShowRealnamePopup = [[NSUserDefaults standardUserDefaults] boolForKey:kBMSShouldShowRealnamePopup]; // 是否达到弹窗时间（标记）
    if (hasForcedRealname == YES && shouldShowRealnamePopup == NO){
        // 不强制实名
        if (completion) completion(NO);
        return;
    }
    
    
    
    if ([BMSInitializer shared].launchModel.rnAuth == 1) {
        // 不强制实名
        if (completion) completion(NO);
        return;
    }

    // 需要实名弹窗
    BMSAuthManager *manager = [[BMSAuthManager alloc] init];
    [manager showRealnamePopupWithCompletion:^(BOOL success) {
        if (completion) {
            completion([BMSInitializer shared].didRealnameAuth);
        }

        if (!success) {
            // ⚠️ 可选处理：退出、提示、记录日志等
            NSLog(@"[BMS] 用户实名失败或取消");
        }
    }];
}

@end
